<template>
  <a-modal title="选择转化追踪" v-model:visible="visible" width="1000px">
    <div class="modal-header">
      <div class="title-area"></div>
      <div class="actions">
        <a-button type="primary" @click="$emit('add-new')">
          <template #icon><plus-outlined /></template>
          新建转化追踪
        </a-button>
      </div>
    </div>

    <div class="account-conversion-container">
      <div class="account-list">
        <h3>账号列表</h3>
        <a-list :dataSource="accountList" :rowKey="(item) => item.id" class="account-list-content">
          <template #renderItem="{ item }">
            <a-list-item :class="{ active: selectedAccountId === item.id }" @click="handleSelectAccount(item)">
              <div class="account-item">
                <div class="account-info">
                  <div class="account-name" :title="item.name">{{ item.name }}</div>
                  <div class="account-id">ID: {{ item.id }}</div>
                </div>
                <a-badge
                  v-if="getAccountSelectedCount(item.id) > 0"
                  :count="getAccountSelectedCount(item.id)"
                  style="margin-left: 8px"
                />
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
      <div class="conversion-list">
        <div class="conversion-list-header">
          <h3>转化追踪列表</h3>
          <a-button type="link" @click="refreshConversionList" :disabled="!selectedAccountId">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
        </div>
        <div v-if="loading" class="loading-container">
          <a-spin />
        </div>
        <div v-else-if="!selectedAccountId" class="empty-tip">请先选择左侧账号</div>
        <a-table
          v-else
          :columns="conversionColumns"
          :dataSource="conversionList"
          rowKey="conversionId"
          :pagination="{
            pageSize: pageSize,
            total: totalConversions,
            current: currentPage,
            onChange: handlePageChange,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '50'],
            onShowSizeChange: handlePageSizeChange,
          }"
          :rowSelection="{
            type: 'radio',
            selectedRowKeys: currentAccountSelectedKeys,
            preserveSelectedRowKeys: true,
            onChange: onSelectChange,
            getCheckboxProps: getCheckboxProps,
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'conversionStatus'">
              <a-tag :color="getStatusColor(record.conversionStatus)">
                {{ getStatusText(record.conversionStatus) }}
              </a-tag>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <div class="selected-summary" v-if="tempSelectedConversions.length > 0">
      <div>已选择 {{ tempSelectedConversions.length }} 个转化追踪</div>
      <a-button type="link" @click="clearAllSelected">清空所有</a-button>
    </div>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :disabled="tempSelectedConversions.length === 0" @click="handleConfirm" style="margin-left: 8px">
        确定 (已选 {{ tempSelectedConversions.length }} 个)
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined, ReloadOutlined } from "@ant-design/icons-vue";

import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";

const store = batchCreateAdStore();

// import { queryConversions } from "@/api/adx-tool";

// queryConversions({
//   "AccountId": 22455,
//     "conversionSource":1,
//     "conversionType": 3
// }).then((res) => {
//   console.log(res);
// });

console.log("加载转化追踪选择组件");

// 账号接口定义
interface AccountItem {
  id: number;
  name: string;
}

// 转化追踪接口定义
interface ConversionItem {
  id?: number;
  conversionId: number;
  conversionName: string;
  conversionType: number;
  trackingType: number;
  conversionSource: number;
  conversionStatus: number;
  customerId: number;
  sourceType: number;
  appId?: number;
}

// 定义 props，接收父组件传递的已选转化追踪和账号列表
const props = defineProps({
  selectedConversions: {
    type: Array,
    default: () => [],
  },
  accountList: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "select", "add-new"]);
const visible = ref(false);
const loading = ref(false);
// 使用传入的账号列表或从 store 获取
const accountList = ref<AccountItem[]>([]);

// 在组件挂载时从 props 或 store 获取账号列表
onMounted(() => {
  if (props.accountList && props.accountList.length > 0) {
    accountList.value = props.accountList as AccountItem[];
  } else if (store.AccountItems && store.AccountItems.length > 0) {
    accountList.value = store.AccountItems as AccountItem[];
  } else {
    // 如果 props 和 store 中都没有账号，使用默认账号（仅用于开发测试）
    accountList.value = [
      { id: 1, name: "广告账号A" },
      { id: 2, name: "广告账号B" },
    ];
  }
});

const selectedAccountId = ref<number | null>(null);
const conversionList = ref<ConversionItem[]>([]);
const allSelectedConversions = ref<ConversionItem[]>([]); // 实际已选转化追踪（确认后的）
const tempSelectedConversions = ref<ConversionItem[]>([]); // 临时选择的转化追踪（确认前的）
const currentPage = ref(1);
const pageSize = ref(10);
const totalConversions = ref(0);

// 转化追踪列表列定义
const conversionColumns = [
  { title: "ID", dataIndex: "conversionId", key: "conversionId", width: 80 },
  { title: "转化追踪名称", dataIndex: "conversionName", key: "conversionName" },
  { title: "转化类型", dataIndex: "conversionType", key: "conversionType" },
  { title: "状态", dataIndex: "conversionStatus", key: "conversionStatus", width: 100 },
];

// 显示弹窗 - 确保选择的转化追踪能够正确回显
const show = () => {
  visible.value = true;

  // 从父组件获取最新的已选转化追踪
  if (props.selectedConversions && Array.isArray(props.selectedConversions)) {
    // 始终使用父组件传递的最新数据
    allSelectedConversions.value = JSON.parse(JSON.stringify(props.selectedConversions));
    tempSelectedConversions.value = JSON.parse(JSON.stringify(props.selectedConversions));
  } else {
    // 如果没有传递转化追踪，则清空
    allSelectedConversions.value = [];
    tempSelectedConversions.value = [];
  }

  // 根据已选转化追踪决定应该选择哪个账号
  if (tempSelectedConversions.value.length > 0) {
    // 从已选转化追踪中获取第一个账号ID
    const firstConversion = tempSelectedConversions.value[0];
    const accountId = Math.floor(firstConversion.conversionId / 100);
    
    // 检查该账号是否在账号列表中
    const accountExists = accountList.value.some(acc => acc.id === accountId);
    
    if (accountExists) {
      selectedAccountId.value = accountId;
    } else if (accountList.value.length > 0) {
      // 如果账号不存在，选择第一个可用账号
      selectedAccountId.value = accountList.value[0].id;
    }
  } else if (!selectedAccountId.value && accountList.value.length > 0) {
    // 如果没有选择转化追踪且没有选择账号，则选择第一个账号
    selectedAccountId.value = accountList.value[0].id;
  }

  // 重置页码并加载数据
  currentPage.value = 1;
  if (selectedAccountId.value) {
    fetchConversionList(selectedAccountId.value, 1);
  }
};

// 隐藏弹窗
const hide = () => {
  visible.value = false;
};

// 获取数据
const getData = () => {
  return allSelectedConversions.value;
};

// 取消选择
const handleCancel = () => {
  hide();
};

// 清空所有选择
const clearAllSelected = () => {
  tempSelectedConversions.value = [];
};

// 确认选择
const handleConfirm = () => {
  if (tempSelectedConversions.value.length === 0) {
    message.error("请至少选择一个转化追踪");
    return;
  }

  // 获取所有账号ID
  const allAccountIds = accountList.value.map((account) => account.id);

  // 检查每个账号是否都选择了转化追踪
  const accountsWithoutConversions = allAccountIds.filter((accountId) => {
    return !tempSelectedConversions.value.some((conversion) => Math.floor(conversion.conversionId / 100) === accountId);
  });

  if (accountsWithoutConversions.length > 0) {
    const accountNames = accountList.value
      .filter((account) => accountsWithoutConversions.includes(account.id))
      .map((a) => a.name)
      .join("、");

    message.error(`以下账号未选择转化追踪: ${accountNames}`);
    return;
  }

  // 将临时选择保存为实际选择
  allSelectedConversions.value = JSON.parse(JSON.stringify(tempSelectedConversions.value));
  emit("select", allSelectedConversions.value);
  hide();
};

// 当前账号已选转化追踪的ID
const currentAccountSelectedKeys = computed(() => {
  const accountConversions = tempSelectedConversions.value.filter(
    (conversion) => Math.floor(conversion.conversionId / 100) === selectedAccountId.value
  );

  // 只返回一个ID（如果有）
  return accountConversions.length > 0 ? [accountConversions[0].conversionId] : [];
});

// 获取指定账号已选转化追踪数量
const getAccountSelectedCount = (accountId: number) => {
  return tempSelectedConversions.value.filter((conversion) => Math.floor(conversion.conversionId / 100) === accountId).length;
};

// 处理账号选择
const handleSelectAccount = (account: AccountItem) => {
  if (selectedAccountId.value === account.id) return; // 避免重复点击

  selectedAccountId.value = account.id;
  currentPage.value = 1;
  fetchConversionList(account.id, 1);
};

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  if (selectedAccountId.value) {
    fetchConversionList(selectedAccountId.value, page);
  }
};

// 处理每页数量变化
const handlePageSizeChange = (current: number, size: number) => {
  pageSize.value = size;
  currentPage.value = 1; // 改变每页数量时重置为第一页
  if (selectedAccountId.value) {
    fetchConversionList(selectedAccountId.value, 1);
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return "启用";
    case 2:
      return "暂停";
    case 3:
      return "审核中";
    default:
      return "未知";
  }
};

// 刷新转化追踪列表
const refreshConversionList = () => {
  if (!selectedAccountId.value) return;

  // 重新加载当前账号的转化追踪列表
  fetchConversionList(selectedAccountId.value, currentPage.value, true);
};

// 获取转化追踪列表
const fetchConversionList = (accountId: number, page = 1, isRefresh = false) => {
  if (!accountId) return;

  loading.value = true;

  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据，使用接口中的格式
    const conversions: ConversionItem[] = [];
    const conversionTypes = [1, 2, 3, 4, 5]; // 不同的转化类型
    const trackingTypes = [1, 2, 3, 4, 5]; // 不同的跟踪类型
    const statusTypes = [1, 2, 3]; // 不同的状态类型

    const total = 35; // 总数据量
    const start = (page - 1) * pageSize.value;
    const end = Math.min(start + pageSize.value, total);

    for (let i = start; i < end; i++) {
      const conversionId = accountId * 100 + i + 1;
      conversions.push({
        conversionId: conversionId,
        conversionName: `转化追踪${conversionId}`,
        conversionType: conversionTypes[i % conversionTypes.length],
        trackingType: trackingTypes[i % trackingTypes.length],
        conversionSource: i % 2 + 1, // 1:APP 2:网址
        conversionStatus: statusTypes[i % statusTypes.length],
        customerId: accountId,
        sourceType: i % 3, // 0:自建，1:授权，2:授权撤回
        appId: 48000 + i
      });
    }

    totalConversions.value = total;
    conversionList.value = conversions;
    loading.value = false;
    
    // 确保选择的转化追踪在列表中存在时能够显示为选中状态
    ensureSelectedConversionsExist();
  }, 500);
};

// 添加方法确保已选择的转化追踪在当前列表中存在
const ensureSelectedConversionsExist = () => {
  if (!selectedAccountId.value) return;
  
  // 获取当前账号的已选择转化追踪
  const currentAccountSelected = tempSelectedConversions.value.find(
    (conversion) => Math.floor(conversion.conversionId / 100) === selectedAccountId.value
  );
  
  // 如果已有选择，检查是否在当前列表中
  if (currentAccountSelected) {
    const existsInCurrentList = conversionList.value.some(
      (item) => item.conversionId === currentAccountSelected.conversionId
    );
    
    // 如果不在当前列表中，且列表不为空，那么需要加载包含该项的页面
    if (!existsInCurrentList && conversionList.value.length > 0) {
      // 计算项目应该在哪一页
      const itemIndex = Math.floor((currentAccountSelected.conversionId % 100) - 1);
      const page = Math.floor(itemIndex / pageSize.value) + 1;
      
      // 如果页码有效且不是当前页，则切换到该页
      if (page > 0 && page <= Math.ceil(totalConversions.value / pageSize.value) && page !== currentPage.value) {
        currentPage.value = page;
        fetchConversionList(selectedAccountId.value, page);
      }
    }
  }
};

// 处理转化追踪选择 - 修改选择逻辑确保正确存储
const onSelectChange = (selectedKeys: string[], selectedRows: ConversionItem[]) => {
  if (!selectedAccountId.value) return;
  
  // 移除当前账号中已有的转化追踪
  tempSelectedConversions.value = tempSelectedConversions.value.filter((conversion) => {
    return Math.floor(conversion.conversionId / 100) !== selectedAccountId.value;
  });

  // 添加当前选中的转化追踪（如果有）
  if (selectedRows.length > 0) {
    const selectedRow = selectedRows[0]; // 单选模式下只取第一个
    if (selectedRow && typeof selectedRow === "object" && "conversionId" in selectedRow) {
      tempSelectedConversions.value.push(selectedRow);
    }
  }
};

// 获取状态标签颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case 1:
      return "green";
    case 2:
      return "orange";
    case 3:
      return "blue";
    default:
      return "default";
  }
};

// 获取复选框属性
const getCheckboxProps = (record: ConversionItem) => {
  return {
    disabled: false, // 可以根据需要设置禁用条件
    name: record.conversionId.toString(),
  };
};

// 添加更新已选转化追踪的方法
const updateSelectedConversions = (conversions: ConversionItem[]) => {
  if (Array.isArray(conversions)) {
    allSelectedConversions.value = JSON.parse(JSON.stringify(conversions));

    // 如果弹窗打开中，也更新临时选择
    if (visible.value) {
      tempSelectedConversions.value = JSON.parse(JSON.stringify(conversions));
    }
  }
};

// 添加更新账号列表的方法
const updateAccountList = (accounts: AccountItem[]) => {
  if (Array.isArray(accounts) && accounts.length > 0) {
    accountList.value = accounts;

    // 如果当前选中的账号不在新的账号列表中，重置选中账号
    if (selectedAccountId.value) {
      const accountExists = accounts.some((acc) => acc.id === selectedAccountId.value);
      if (!accountExists && accounts.length > 0) {
        selectedAccountId.value = accounts[0].id;
        currentPage.value = 1;
        fetchConversionList(accounts[0].id, 1);
      }
    }

    // 过滤临时选择的转化追踪，移除不存在账号的转化追踪
    const accountIds = new Set(accounts.map((acc) => acc.id));
    tempSelectedConversions.value = tempSelectedConversions.value.filter((conversion) => {
      const conversionAccountId = Math.floor(conversion.conversionId / 100);
      return accountIds.has(conversionAccountId);
    });

    // 同步到实际选择
    allSelectedConversions.value = JSON.parse(JSON.stringify(tempSelectedConversions.value));
  }
};

// 添加一个方法用于添加新创建的转化追踪到列表中
const addNewConversion = (newConversion: ConversionItem) => {
  // 如果当前选中的账号与新转化追踪的账号相同，刷新列表
  const conversionAccountId = Math.floor(newConversion.conversionId / 100);
  if (selectedAccountId.value === conversionAccountId) {
    refreshConversionList();
  }
};

// 暴露给父组件的方法
defineExpose({
  show,
  hide,
  getData,
  updateSelectedConversions,
  updateAccountList,
  addNewConversion,
});
</script>

<style scoped>
.account-conversion-container {
  display: flex;
  height: 400px;
}

.account-list {
  width: 250px;
  border-right: 1px solid #f0f0f0;
  padding-right: 16px;
  overflow-x: auto;
  overflow-y: auto;
}

.account-list-content {
  height: calc(100% - 40px);
  overflow-y: auto;
}

.account-item {
  cursor: pointer;
  width: 100%;
  display: flex;
  align-items: center;
  overflow: hidden;
  padding: 0 8px;
}

.account-info {
  flex: 1;
  overflow: hidden;
}

.account-name {
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.account-id {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.conversion-list {
  flex: 1;
  padding-left: 16px;
  overflow-y: auto;
}

.loading-container,
.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 40px);
  color: #999;
}

.active {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.selected-summary {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.selected-summary div {
  flex: 1;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title-area {
  flex: 1;
}

.title-area h3 {
  margin: 0;
}

.actions {
  margin-left: 16px;
}

.conversion-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
</style>
